// Activity Report Page

import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Typography,
  Radio,
  DatePicker,
  Button,
  Spin,
  Alert,
  Row,
  Col,
  Statistic,
  Space,
  Tag,
  Divider,
  Tabs,
  Badge
} from 'antd';
import { 
  BarChartOutlined,
  ClockCircleOutlined,
  UserOutlined,
  MessageOutlined,
  SyncOutlined,
  ExportOutlined,
  CalendarOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined
} from '@ant-design/icons';
import moment from 'moment';
import api from '../../services/api';

const { Title } = Typography;
const { RangePicker } = DatePicker;

// 格式化时间为小时:分钟:秒
const formatTime = (seconds) => {
  if (!seconds) return '00:00:00';
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const remainingSeconds = seconds % 60;
  
  return [
    hours.toString().padStart(2, '0'),
    minutes.toString().padStart(2, '0'),
    remainingSeconds.toString().padStart(2, '0')
  ].join(':');
};

// 格式化时间为小时和分钟
const formatTimeHM = (seconds) => {
  if (!seconds) return '0小时0分钟';
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  
  return `${hours}小时${minutes}分钟`;
};

const ActivityReport = () => {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [period, setPeriod] = useState('week');
  const [reportData, setReportData] = useState([]);
  const [summaryData, setSummaryData] = useState({
    totalUsers: 0,
    totalActiveTime: 0,
    totalMessages: 0,
    averageResponseRate: 0,
    averageResponseTime: 0
  });
  const [selectedUser, setSelectedUser] = useState(null);
  const [userDetail, setUserDetail] = useState(null);
  const [userDetailLoading, setUserDetailLoading] = useState(false);
  const [customDateRange, setCustomDateRange] = useState(null);
  const [activeTab, setActiveTab] = useState('1');

  // 加载活动报告数据
  useEffect(() => {
    fetchActivityReport();
  }, [period, customDateRange]);

  // 获取活动报告
  const fetchActivityReport = async () => {
    try {
      setLoading(true);
      setError(null);
      
      // 构建请求参数
      let params = { period };
      
      // 如果选择了自定义日期范围
      if (period === 'custom' && customDateRange) {
        params.startDate = customDateRange[0].format('YYYY-MM-DD');
        params.endDate = customDateRange[1].format('YYYY-MM-DD');
      }
      
      const response = await api.get('/activity/all/report', { params });
      setReportData(response.data);
      
      // 计算汇总数据
      const summary = calculateSummary(response.data);
      setSummaryData(summary);
    } catch (error) {
      console.error('获取活动报告失败:', error);
      setError('获取活动报告数据失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 获取用户详细数据
  const fetchUserDetail = async (userId) => {
    try {
      setUserDetailLoading(true);
      
      // 构建请求参数
      let params = { period };
      
      // 如果选择了自定义日期范围
      if (period === 'custom' && customDateRange) {
        params.startDate = customDateRange[0].format('YYYY-MM-DD');
        params.endDate = customDateRange[1].format('YYYY-MM-DD');
      }
      
      const response = await api.get(`/activity/user/${userId}/report`, { params });
      setUserDetail(response.data);
      setSelectedUser(userId);
    } catch (error) {
      console.error('获取用户详细数据失败:', error);
    } finally {
      setUserDetailLoading(false);
    }
  };

  // 计算汇总数据
  const calculateSummary = (data) => {
    if (!data || data.length === 0) {
      return {
        totalUsers: 0,
        totalActiveTime: 0,
        totalMessages: 0,
        averageResponseRate: 0,
        averageResponseTime: 0
      };
    }
    
    let totalActiveTime = 0;
    let totalMessages = 0;
    let responseRateSum = 0;
    let responseTimeSum = 0;
    let validUsers = 0;
    
    data.forEach(report => {
      const summary = report.summary;
      totalActiveTime += summary.totalActiveTime || 0;
      totalMessages += (summary.totalMessagesSent || 0) + (summary.totalMessagesReceived || 0);
      
      if (summary.responseRate !== undefined && summary.responseRate !== null) {
        responseRateSum += summary.responseRate;
        validUsers++;
      }
      
      if (summary.averageResponseTime !== undefined && summary.averageResponseTime !== null) {
        responseTimeSum += summary.averageResponseTime;
        // 不重复计数validUsers，因为通常两个指标都有数据或者都没有
      }
    });
    
    return {
      totalUsers: data.length,
      totalActiveTime,
      totalMessages,
      averageResponseRate: validUsers > 0 ? (responseRateSum / validUsers) : 0,
      averageResponseTime: validUsers > 0 ? (responseTimeSum / validUsers) : 0
    };
  };

  // 处理周期选择变化
  const handlePeriodChange = (e) => {
    const value = e.target.value;
    setPeriod(value);
    
    // 重置自定义日期范围
    if (value !== 'custom') {
      setCustomDateRange(null);
    }
  };

  // 处理日期范围变化
  const handleDateRangeChange = (dates) => {
    setCustomDateRange(dates);
  };

  // 处理导出报告
  const handleExportReport = () => {
    // 这里可以实现导出CSV或Excel功能
    alert('导出报告功能正在开发中');
  };

  // 表格列定义
  const columns = [
    {
      title: '用户',
      dataIndex: ['user', 'name'],
      key: 'name',
      render: (text, record) => (
        <Space>
          <UserOutlined />
          <span>{text}</span>
          {record.user.whatsappStatus === 'connected' && (
            <Badge status="success" text="在线" />
          )}
        </Space>
      )
    },
    {
      title: '部门',
      dataIndex: ['user', 'department'],
      key: 'department',
      render: (text) => text || '-'
    },
    {
      title: '活跃时长',
      dataIndex: ['summary', 'totalActiveTime'],
      key: 'activeTime',
      sorter: (a, b) => a.summary.totalActiveTime - b.summary.totalActiveTime,
      render: (time) => (
        <Space>
          <ClockCircleOutlined />
          <span>{formatTimeHM(time)}</span>
        </Space>
      )
    },
    {
      title: '会话次数',
      dataIndex: ['summary', 'totalSessionStarts'],
      key: 'sessions',
      sorter: (a, b) => a.summary.totalSessionStarts - b.summary.totalSessionStarts,
      render: (count) => count || 0
    },
    {
      title: '消息(发送/接收)',
      key: 'messages',
      render: (_, record) => (
        <Space>
          <span>{record.summary.totalMessagesSent || 0}</span>
          <span>/</span>
          <span>{record.summary.totalMessagesReceived || 0}</span>
        </Space>
      )
    },
    {
      title: '响应率',
      dataIndex: ['summary', 'responseRate'],
      key: 'responseRate',
      sorter: (a, b) => a.summary.responseRate - b.summary.responseRate,
      render: (rate) => {
        // 根据响应率设置不同颜色
        let color = 'green';
        if (rate < 0.6) color = 'red';
        else if (rate < 0.8) color = 'orange';
        
        return (
          <Tag color={color}>
            {`${(rate * 100).toFixed(1)}%`}
          </Tag>
        );
      }
    },
    {
      title: '平均响应时间',
      dataIndex: ['summary', 'averageResponseTime'],
      key: 'responseTime',
      sorter: (a, b) => a.summary.averageResponseTime - b.summary.averageResponseTime,
      render: (time) => {
        // 根据响应时间设置不同颜色
        let color = 'green';
        if (time > 300) color = 'red'; // 5分钟以上
        else if (time > 120) color = 'orange'; // 2分钟以上
        
        return (
          <Tag color={color}>
            {time ? `${Math.floor(time / 60)}分${time % 60}秒` : '-'}
          </Tag>
        );
      }
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button 
          type="link" 
          onClick={() => fetchUserDetail(record.user.id)}
          loading={userDetailLoading && selectedUser === record.user.id}
        >
          详情
        </Button>
      )
    }
  ];

  // 渲染用户详情
  const renderUserDetail = () => {
    if (!userDetail) return null;
    
    const { user, summary, details, period } = userDetail;
    
    return (
      <Card
        title={
          <Space>
            <UserOutlined />
            <span>{user.name} 的活动详情</span>
            {user.whatsappStatus === 'connected' ? (
              <Tag color="success" icon={<CheckCircleOutlined />}>在线</Tag>
            ) : (
              <Tag color="default" icon={<CloseCircleOutlined />}>离线</Tag>
            )}
          </Space>
        }
        extra={
          <Button icon={<ExportOutlined />} onClick={handleExportReport}>
            导出详情
          </Button>
        }
        style={{ marginTop: 16 }}
      >
        <Row gutter={[16, 16]}>
          <Col span={6}>
            <Statistic
              title="总活跃时长"
              value={formatTimeHM(summary.totalActiveTime)}
              prefix={<ClockCircleOutlined />}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="总消息数"
              value={summary.totalMessagesSent + summary.totalMessagesReceived}
              prefix={<MessageOutlined />}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="会话次数"
              value={summary.totalSessionStarts}
              prefix={<CalendarOutlined />}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="响应率"
              value={`${(summary.responseRate * 100).toFixed(1)}%`}
              valueStyle={summary.responseRate >= 0.8 ? { color: '#3f8600' } : { color: '#cf1322' }}
              prefix={summary.responseRate >= 0.8 ? <CheckCircleOutlined /> : <CloseCircleOutlined />}
            />
          </Col>
        </Row>
        
        <Divider />
        
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <Tabs.TabPane tab="详细数据" key="1">
            <Table
              dataSource={details}
              rowKey="date"
              pagination={false}
              columns={[
                {
                  title: '日期',
                  dataIndex: 'date',
                  key: 'date'
                },
                {
                  title: '活跃时长',
                  dataIndex: 'activeTime',
                  key: 'activeTime',
                  render: (time) => formatTime(time)
                },
                {
                  title: '发送消息',
                  dataIndex: 'messagesSent',
                  key: 'messagesSent'
                },
                {
                  title: '接收消息',
                  dataIndex: 'messagesReceived',
                  key: 'messagesReceived'
                },
                {
                  title: '会话次数',
                  dataIndex: 'sessionStarts',
                  key: 'sessionStarts'
                },
                {
                  title: '响应率',
                  dataIndex: 'responseRate',
                  key: 'responseRate',
                  render: (rate) => `${(rate * 100).toFixed(1)}%`
                },
                {
                  title: '平均响应时间',
                  dataIndex: 'averageResponseTime',
                  key: 'averageResponseTime',
                  render: (time) => time ? `${Math.floor(time / 60)}分${time % 60}秒` : '-'
                }
              ]}
            />
          </Tabs.TabPane>
        </Tabs>
      </Card>
    );
  };

  return (
    <div className="activity-report-container">
      <Card
        title={
          <Space>
            <BarChartOutlined />
            <span>用户活动报告</span>
          </Space>
        }
        extra={
          <Space>
            <Radio.Group value={period} onChange={handlePeriodChange}>
              <Radio.Button value="day">今日</Radio.Button>
              <Radio.Button value="week">本周</Radio.Button>
              <Radio.Button value="month">本月</Radio.Button>
              <Radio.Button value="custom">自定义</Radio.Button>
            </Radio.Group>
            
            {period === 'custom' && (
              <RangePicker 
                value={customDateRange}
                onChange={handleDateRangeChange}
                style={{ width: 240 }}
              />
            )}
            
            <Button 
              icon={<SyncOutlined />} 
              onClick={fetchActivityReport}
              loading={loading}
            >
              刷新
            </Button>
            
            <Button 
              icon={<ExportOutlined />}
              onClick={handleExportReport}
            >
              导出报告
            </Button>
          </Space>
        }
      >
        {error && (
          <Alert
            message="数据加载错误"
            description={error}
            type="error"
            showIcon
            style={{ marginBottom: 16 }}
          />
        )}
        
        <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
          <Col span={4}>
            <Card>
              <Statistic
                title="销售人员"
                value={summaryData.totalUsers}
                prefix={<UserOutlined />}
              />
            </Card>
          </Col>
          <Col span={5}>
            <Card>
                <Statistic
                title="总活跃时长"
                value={formatTimeHM(summaryData.totalActiveTime)}
                prefix={<ClockCircleOutlined />}
                />
              </Card>
            </Col>
          <Col span={5}>
            <Card>
                <Statistic
                title="总消息量"
                value={summaryData.totalMessages}
                  prefix={<MessageOutlined />}
                />
              </Card>
            </Col>
          <Col span={5}>
            <Card>
                <Statistic
                title="平均响应率"
                value={`${(summaryData.averageResponseRate * 100).toFixed(1)}%`}
                valueStyle={
                  summaryData.averageResponseRate >= 0.8 
                    ? { color: '#3f8600' } 
                    : { color: '#cf1322' }
                }
                />
              </Card>
            </Col>
          <Col span={5}>
            <Card>
                <Statistic
                title="平均响应时间"
                value={
                  summaryData.averageResponseTime 
                    ? `${Math.floor(summaryData.averageResponseTime / 60)}分${summaryData.averageResponseTime % 60}秒` 
                    : '-'
                }
                />
              </Card>
            </Col>
          </Row>

        <Spin spinning={loading}>
          <Table 
            dataSource={reportData}
            columns={columns}
            rowKey={record => record.user.id}
            pagination={{ pageSize: 10 }}
          />
        </Spin>
        
        {renderUserDetail()}
          </Card>
    </div>
  );
};

export default ActivityReport; 
